package net.wofly.common.condition;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.JsonDynamicSpecifications;
import net.wofly.common.util.GeneralHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 查询条件工具类<br/>
 * Copyright (c) 2014 , 北京可思云海科技有限公司<br/>
 * 2014-10-29 上午10:21:47
 * @author gyj@kscloud.com
 * @version V1.0
 */
@val
@Slf4j
public class ConditionUtil {

	/**
	 * 
	 * 
	 * @param jsonStr
	 * @param clazz
	 * @return	ResultBean<Condition>
	 */
	public static <T> ReturnBean<Condition> buildCondition(String jsonStr, Class clazz){
		if(!StringUtils.isEmpty(jsonStr)){
			Condition condition  = XiNiaoJSON.parseObject(jsonStr, Condition.class);
			try{
				Specification<T> specification  = JsonDynamicSpecifications.builder(condition, clazz);
				condition.setSpecification(specification);
				if (condition != null && condition.getOrderConditions() != null && condition.getOrderConditions().size() > 0) {
					Collections.sort(condition.getOrderConditions(), new Comparator<OrderCondition>() {
						@Override
						public int compare(OrderCondition o1, OrderCondition o2) {
							if (o1.getSortNo() < o2.getSortNo()) {
								return -1;
							} else if (o1.getSortNo() == o2.getSortNo()) {
								return 0;
							} else {
								return 1;
							}
						}
					});
				}

				if(condition.getOrderConditions()!=null&&condition.getOrderConditions().size()>0){
					List<Order> orderList = new ArrayList<Order>();
					for(OrderCondition orderCondition :condition.getOrderConditions()){
						Order order = new Order("DESC".equalsIgnoreCase(orderCondition.getOrder())?Direction.DESC:Direction.ASC, orderCondition.getAttrName());
						orderList.add(order);
					}
					condition.setSort(new Sort(orderList));
				}
			}catch (Exception e){
				log.error(e.getMessage());
				return new ReturnBean<Condition>(ResultCode.ERROR_DATA,"查询条件解析错误!",condition);
			}
			val resultBean = new ReturnBean<Condition>(ResultCode.SUCCESS,"",condition);
			return resultBean;
		}else{
			return new ReturnBean<Condition>(ResultCode.SUCCESS,"输入字符串为空!",new Condition());
		}
	}
	
	/**
	 * 把json字符串转换为Condition对象
	 * @param condition
	 * @return	Condition    
	 */
	public static Condition parseCondition(String condition){
		if(GeneralHelper.isTrimStrNotEmpty(condition)){
			return XiNiaoJSON.parseObject(condition, Condition.class);
		}
		return null;
	}

}
